package com.windmt.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.windmt.util.JsoupUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;

/**
 * @author Jean
 * @date
 * @des
 */
@Component
@AllArgsConstructor
public class TokenFilter implements GlobalFilter, Ordered {

    private final ObjectMapper objectMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        String token = String.valueOf(exchange.getRequest().getHeaders().get("token"));
        clean(exchange);

        if (StringUtils.isBlank(token)) {
            ServerHttpResponse response = exchange.getResponse();

            HashMap<String, Object> result = new HashMap<>(16);
            result.put("code", 423);
            result.put("msg", "认证失败.");
            result.put("data", null);
            try {
                return response.writeWith(Mono.just(response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result))));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return chain.filter(exchange);
    }


    /**
     * Xss 过滤
     *
     * @param exchange
     */
    private void clean(ServerWebExchange exchange) {

        Object requestBody = exchange.getAttribute("cachedRequestBodyObject");
        if (null != requestBody) {
            JsoupUtil.clean(requestBody.toString());
        }

        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach((key, value) -> JsoupUtil.clean(value.toString()));
        }

        MultiValueMap<String, String> params = request.getQueryParams();
        if (!CollectionUtils.isEmpty(params)) {
            params.forEach((key, value) -> JsoupUtil.clean(value.toString()));
        }

    }

    @Override
    public int getOrder() {
        return -100;
    }
}
